<template>
  <div v-if="visible">
    <el-tooltip class="tool-item" content="转成统计图" placement="top">
      <a @click="toAnalysisChart"><i class="el-icon-pie-chart"></i></a>
    </el-tooltip>
    <el-tooltip class="tool-item" :content="`${rotate ? '展开' : '收起'}搜索框`" placement="top">
      <a @click="toggleFilter"><i :class="rotate ? 'ro' : ''" class="el-icon-arrow-up"></i></a>
    </el-tooltip>
    <el-tooltip class="tool-item" content="下载表格数据" placement="top">
      <a @click="downloadExcel"><i class="el-icon-download"></i></a>
    </el-tooltip>
    <el-tooltip class="tool-item" content="设置表格" placement="top">
      <el-popover placement="bottom-end" title="设置表格" trigger="click">
        <a slot="reference"><i class="el-icon-setting"></i></a>
        <el-descriptions :column="1" size="mini" border>
          <el-descriptions-item label="是否显示">
            <el-checkbox-group v-model="showList" @change="handlerOptionsChange">
              <div><el-checkbox label="border">纵向边框</el-checkbox></div>
              <div><el-checkbox label="showHeader">表头</el-checkbox></div>
              <div><el-checkbox label="showSummary">合计行</el-checkbox></div>
            </el-checkbox-group>
          </el-descriptions-item>
          <el-descriptions-item label="Table尺寸">
            <el-select v-model="size" size="mini" @change="handlerOptionsChange">
              <el-option label="default" :value="undefined"></el-option>
              <el-option label="medium" value="medium"></el-option>
              <el-option label="small" value="small"></el-option>
              <el-option label="mini" value="mini"></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="固定左边">
            <el-select v-model="leftFixed" size="mini" multiple collapse-tags placeholder="请选择元素" @change="handlerOptionsChange">
              <el-option v-for="item in columns" v-bind="item.fixedOption"
                :disabled="rightFixed.includes(item.fixedOption.value)" />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="固定右边">
            <el-select v-model="rightFixed" size="mini" multiple collapse-tags placeholder="请选择元素" @change="handlerOptionsChange">
              <el-option v-for="item in columns" v-bind="item.fixedOption"
                :disabled="leftFixed.includes(item.fixedOption.value)" />
            </el-select>
          </el-descriptions-item>
        </el-descriptions>
      </el-popover>
    </el-tooltip>
    <el-tooltip class="tool-item" content="设置列" placement="top">
      <el-popover placement="bottom-end" trigger="click" @show="showColumnSetting" @hide="hideColumnSetting">
        <a slot="reference"><i class="el-icon-s-operation"></i></a>
        <table class="tablexxxxx">
          <thead>
            <tr>
              <td></td>
              <td><el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" />
              </td>
              <td>列对齐</td>
              <td>列宽度</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(field, i) in sortColumns" :key="i">
              <td><i class="handle el-icon-rank"></i></td>
              <td class="pl20">
                <el-checkbox v-model="field.show" @change="handleFieldsChange">
                  {{ field.label }}
                </el-checkbox>
              </td>
              <td>
                <el-select v-model="field.align" style="width: 90px;" size="mini" @change="handleColumnChange">
                  <el-option label="靠左" :value="undefined"></el-option>
                  <el-option label="居中" value="center"></el-option>
                  <el-option label="靠右" value="right"></el-option>
                </el-select>
              </td>
              <td>
                <el-input v-model="field.columnWidth" style="width: 80px;" size="mini" @change="handleColumnChange" />
              </td>
            </tr>
          </tbody>
        </table>
      </el-popover>
    </el-tooltip>
  </div>
</template>

<script>
import { deepCopy } from '@/utils'
import ExcelExport from 'export-xlsx';
import Sortable from 'sortablejs'
import { SETTINGS_FOR_EXPORT } from '@/utils/exportSetting';
export default {
  props: ['refList'],
  data() {
    return {
      size: '',
      rotate: false,
      visible: true,
      table: {},
      fields: [],
      showList: [],
      leftFixed: [],
      rightFixed: [],
      checkAll: false,
      isIndeterminate: true,
      columns: [],
      sortColumns: []
    }
  },
  methods: {
    async init(table = {}) {
      this.table = table
      const { fields = [] } = this.table
      this.fields = fields.map(({ show = true, ...params }) => ({ ...params, show }))
      const count = this.fields.filter(i => i.show).length;
      this.checkAll = this.fields.length === count
      this.isIndeterminate = this.fields.length > 0 && this.fields.length < count;
      const rightlist = [], leftlist = []
      this.fields.forEach(({ prop, type, label, fixed }) => {
        if (fixed && fixed === 'right') {
          rightlist.push(prop + type + label)
        } else if (fixed) {
          leftlist.push(prop + type + label)
        }
      })
      this.leftFixed = leftlist
      this.rightFixed = rightlist
      if (this.table.showSummary) this.showList.push('showSummary')
      if (this.table.border === undefined || this.table.border) this.showList.push('border')
      if (this.table.showHeader === undefined || this.table.showHeader) this.showList.push('showHeader')

      this.size = this.table.size || ''
      this.visible = this.fields.length > 0
      this.columns = this.fields.filter(i => i.table === undefined || i.table).map(i => {
        const fixedOption = { label: i.label + '列', value: i.prop + i.type + i.label }
        return { ...i, fixedOption }
      })
      await this.$nextTick()
      this.initSort()
      this.sortColumns.forEach(i => {
        const item = table.fields.find(this.isEqualFun(i))
        i.columnWidth = item.columnWidth
      })
    },
    initSort() {
      const dom = document.querySelector('.tablexxxxx tbody')
      if (!dom) return
      new Sortable(dom, {
        animation: 150,
        handle: '.handle',
        onEnd: this.sortEnd
      })
    },
    isEqualFun({ prop, type, label }) {
      return (i) => i.prop === prop && i.type === type && i.label === label
    },
    showColumnSetting() {
      this.sortColumns = this.fields.filter(i => i.table === undefined || i.table)
    },
    hideColumnSetting() {
      this.sortColumns = []
    },
    async sortEnd({ newIndex, oldIndex }) {
      const nIndex = this.fields.findIndex(this.isEqualFun(this.columns[newIndex]))
      const oIndex = this.fields.findIndex(this.isEqualFun(this.columns[oldIndex]))

      this.fields.splice(nIndex, 0, this.fields.splice(oIndex, 1)[0])
      this.columns.splice(newIndex, 0, this.columns.splice(oldIndex, 1)[0])

      this.handleColumnChange()
    },
    toAnalysisChart() {
      console.log('xxxxx')
    },
    downloadExcel() {
      const data = {
        table1: []
      };
      const excelExport = new ExcelExport();
      excelExport.downloadExcel(SETTINGS_FOR_EXPORT, data);
    },
    toggleFilter() {
      this.refList.filter.toggleFilter()
      this.rotate = !this.rotate
    },

    handlerOptionsChange() {
      let table = deepCopy(this.table)
      table.fields = this.fields.map(item => {
        const value = item.prop + item.type + item.label
        if (this.leftFixed.includes(value)) {
          item.fixed = 'left'
        } else if (this.rightFixed.includes(value)) {
          item.fixed = 'right'
        } else {
          item.fixed = undefined
        }
        return { ...item }
      })
      table.size = this.size
      table.border = this.showList.includes('border')
      table.showHeader = this.showList.includes('showHeader')
      table.showSummary = this.showList.includes('showSummary')
      this.$emit('change', table)
    },
    handleColumnChange() {
      let table = deepCopy(this.table)
      table.fields = this.fields.map(item => {
        const data = this.sortColumns.find(this.isEqualFun(item))
        return data || item
      })
      this.$emit('change', table)
    },
    handleCheckAllChange(show) {
      this.columns = this.sortColumns.map(i => ({ ...i, show }))
      this.isIndeterminate = false;
      this.handleColumnChange()
    },
    handleFieldsChange() {
      const checkedCount = this.sortColumns.filter(i => i.show).length;
      this.checkAll = checkedCount === this.sortColumns.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.sortColumns.length;
      this.handleColumnChange()
    }
  }
}
</script>

<style lang="scss" scoped>
.tablexxxxx .handle {
  margin-right: 20px;
  font-size: 16px;
  cursor: move;
}

.pl20 {
  padding-right: 10px;
}

.tool-item {
  margin: 0 10px;

  i {
    cursor: pointer;
    transition: 300ms;
  }

  &:last-child {
    margin-right: 0;
  }

  &:first-child {
    margin-left: 0;
  }

  i.ro {
    transform: rotate(180deg);
  }
}
</style>